package server.DAO.MySQLDAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;
import common.DAO.CategoryDAO;
import common.Objects.Category;

/**
 * The database manipulations and getters for Category.
 * @author Richard Irons
 */
public class MySQLCategoryDAO implements CategoryDAO{
    /**
     * Get category returns a vector of categorys from the database
     * @return A vector of the categorys from the database
     */
    public Vector<Category> getCategorys() {
        Vector<Category> categorys = new Vector<Category>();
        try {
            Connection c = MySQLDAOFactory.createConnection();
            if ( c != null ) {
                Statement statement = c.createStatement();
                ResultSet rs = statement.executeQuery(
                        "SELECT * FROM " + MySQLDAOFactory.DBNAME + "." + "CATEGORY");
                if (rs.isBeforeFirst()){
                    rs.next();
                }
                if (rs.first()){
                    do {
                        Category tempCategory = new Category();
                        tempCategory.setId(rs.getInt("Id"));
                        tempCategory.setName(rs.getString("Name"));
                        categorys.add(tempCategory);
                    }
                    while(rs.next());
                }
                c.close();
            }
        } catch (Exception e){e.printStackTrace();}
        return categorys;
    }
    /**
     * Adds a category to the database.
     * @param category - category to add.
     * @return True if added
     */
    public boolean createCategory(Category category) {        
        return MySQLDAOFactory.dbUpdate(
            "INSERT INTO " + MySQLDAOFactory.DBNAME + "." + "CATEGORY ( "
            + "Id, "
            + "Name "
            + ") VALUES ( "
            + "NULL, "
            + "\"" + category.getName() + "\" "
            + ")");
    }
    /**
     * Delete a category where the id is the same as the input id, limited to 1.
     * @param id - id to delete.
     * @return True if deleted else false.
     */
    public boolean deleteCategory(int id) {
        return MySQLDAOFactory.dbUpdate(
                "DELETE FROM " + MySQLDAOFactory.DBNAME + "." + "CATEGORY WHERE Id = \""
                +id
                +"\" LIMIT 1 ");
    }
}
